﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;

namespace ShevaEngine.Core
{
    /// <summary>
    /// Game Module.
    /// </summary>
    public class ShevaGameModule
    {
        /// <summary>Singleton.</summary>
        public static readonly ShevaGameModule Instance = new ShevaGameModule();

        /// <summary>Game parts.</summary>
        private Stack<IShevaEngineGamePart> GameParts;

        /// <summary>
        /// Actual game part.
        /// </summary>
        public IShevaEngineGamePart ActualGamePart
        {
            get
            {
                if (this.GameParts.Count > 0)
                    return this.GameParts.Peek();

                return null;
            }
        }


        /// <summary>
        /// Constructor.
        /// </summary>
        public ShevaGameModule()
        {
            this.GameParts = new Stack<IShevaEngineGamePart>();            
        }

        /// <summary>
        /// Method add new gamepart on stack.
        /// </summary>
        /// <param name="gamePart"></param>
        public void PushGamePart(IShevaEngineGamePart gamePart)
        {
            gamePart.Activate();

            IShevaEngineGamePart temp = null;

            if (this.GameParts.Count > 0)            
                 temp = this.GameParts.Peek();

            this.GameParts.Push(gamePart);            

            if (temp != null)
                Task.Factory.StartNew(() => temp.Deactivate(), TaskCreationOptions.None);
        }

        /// <summary>
        /// Method pops gamepart from stack.
        /// </summary>
        public void PopGamePart()
        {
            IShevaEngineGamePart temp = this.GameParts.Peek();

            if (temp != null)
                Task.Factory.StartNew(() => temp.Deactivate(), TaskCreationOptions.None);

            if (this.ActualGamePart != null)
                this.ActualGamePart.Activate();
            else
                ShevaEngine.Instance.Exit();
        }

        /// <summary>
        /// Method Update().
        /// </summary>
        /// <param name="gameTime"></param>
        public void Update(GameTime gameTime)
        {
            if (this.ActualGamePart != null)
                this.ActualGamePart.Update(gameTime);
        }

        /// <summary>
        /// Method Draw().
        /// </summary>
        public void Draw()
        {
            if (this.ActualGamePart != null)
                this.ActualGamePart.Draw();
        }
    }
}
